﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web.UI;
using CoreLab.Oracle; //using Devart.Data.Oracle; //using Oracle.DataAccess.Client;

using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxCallback;

using LMD.Constant;
using LMD.Lib.DataClass;
using LMD.Lib.Interface;
using LMD.Lib.Oracle;

public partial class UFTClose : ICPRelationshipPage
{
    public UFTData m_uftData = new UFTData();
    public int m_iEventId = 0;
    public bool bCheckClose = false;
    public bool bSaved = false;
        
    #region Properties
    public String m_sxEventId
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["eid"]))
            {
                return Request.QueryString["eid"];
            }
            else
            {
                return String.Empty;
            }
        }
    }
    #endregion Properties

    #region Event Handlers
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        Page.Title = "ICP Lintasarta: Relationship, Close Event";
        m_iEventId = Context.ReadInt("eid");
        if (!IsPostBack && !IsCallback)
        {
            Session[KSession.UFT_EVENTID] = null;
            InitUFTData();
        }
        //m_iEventId = Context.ReadInt("eid");
        //Session[KSession.UFT_EVENTID] = m_iEventId;
        bCheckClose = DBQuery.EventTable.CheckIsClosed(m_iEventId);
        bSaved = DBQuery.CustomerTable.checkSaveHadir(m_iEventId);
        InitGuestInvitation();
        InitGuest();
    }
    
    protected void cbkClose_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        e.Result = HandleClosing(e.Parameter);
    }
    protected void cbkConfirm_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        e.Result = HandleConfirm(e.Parameter);
    }
    protected void dgCustomerList_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        if (e.Parameters.ToUpper().StartsWith("SAVE"))
        {
            SaveKehadiran();
        }
        else if (e.Parameters.ToUpper().StartsWith("REFRESH"))
        {
            InitGuestInvitation();
        }
    }

    protected void dgGuest_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        HandleGuest(e.Parameters);
    }
    protected void dgGuestSelected_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        if (e.Parameters.ToUpper().StartsWith("INIT"))
        {
            InitSelectedGuest(e.Parameters);
        }
        else if (e.Parameters.ToUpper().StartsWith("SELECT"))
        {
            HandleSelectGuest(e.Parameters);
        }
    }
    #endregion Event Handlers

    #region Custom Methods
    protected override void DoSearch(String sxSearchQuery)
    {
        throw new NotImplementedException();
    }
    private void InitUFTData()
    {
        if (m_iEventId > 0)
        {
            DataTable dtEventTable = DBQuery.EventTable.GetEventDataByID(m_iEventId);
            m_uftData.sxCode = dtEventTable.Rows[0]["CODE"].ToString();
            m_uftData.dtmEventDate = Convert.ToDateTime(dtEventTable.Rows[0]["EVENT_DATE"]);
            m_uftData.iEventId = Convert.ToInt32(dtEventTable.Rows[0]["P_EVENT_ID"]);
            if (dtEventTable.Rows[0]["INVITATION_ATTACHMENT_ID"] == DBNull.Value)
            {
                m_uftData.iInvitationAttachmentId = 0;
            }
            else
            {
                m_uftData.iInvitationAttachmentId = Convert.ToInt32(dtEventTable.Rows[0]["INVITATION_ATTACHMENT_ID"]);
            }
            if (dtEventTable.Rows[0]["EVENT_ATTACHMENT_ID"] == DBNull.Value)
            {
                m_uftData.iEventAttachmentId = 0;
            }
            else
            {
                m_uftData.iEventAttachmentId = Convert.ToInt32(dtEventTable.Rows[0]["EVENT_ATTACHMENT_ID"]);
            }
            if (dtEventTable.Rows[0]["PRESENTATION_ID"] == DBNull.Value)
            {
                m_uftData.iPresentationId = 0;
            }
            else
            {
                m_uftData.iPresentationId = Convert.ToInt32(dtEventTable.Rows[0]["PRESENTATION_ID"]);
            }
            if (dtEventTable.Rows[0]["LOCATION"] != DBNull.Value)
            {
                m_uftData.sxLocation = dtEventTable.Rows[0]["LOCATION"].ToString();
            }
            if (dtEventTable.Rows[0]["START_TIME"] != DBNull.Value)
            {
                m_uftData.dtmStartTime = Convert.ToDateTime(dtEventTable.Rows[0]["START_TIME"]);
            }
            if (dtEventTable.Rows[0]["END_TIME"] != DBNull.Value)
            {
                m_uftData.dtmEndTime = Convert.ToDateTime(dtEventTable.Rows[0]["END_TIME"]);
            }
            m_uftData.BuildFieldSet_UFTData();
        }
    }

    private void InitGuestInvitation()
    {
        String sxCARID = ICPUser.ID;
        //m_iEventId = Convert.ToInt32(Session[KSession.UFT_EVENTID]);
        DataTable dtSelected = DBQuery.CustomerTable.GetCustomerClose(m_iEventId, sxCARID);

        dgCustomerList.DataSource = dtSelected;
        //disini buat nampilin yg selection
        for (int i = 0; i < dtSelected.Rows.Count; i++)
        {
            dgCustomerList.Selection.SetSelectionByKey(
                dtSelected.Rows[i]["T_RELATION_INVITATION_ID"],
                dtSelected.Rows[i]["STATUS_HADIR"].ToString() == "HADIR");
        }
        //
        dgCustomerList.DataBind();
        dgCustomerList.Columns["CUSTOMER_ID"].Visible = false;
        dgCustomerList.Columns["COMPANY_NAME"].Visible = true;
        dgCustomerList.Columns["T_RELATION_INVITATION_ID"].Visible = false;
    }

    //private void SaveKehadiranzzzzzzz()
    //{
        
    //    DBLib dbl = new DBLib();
    //    dbl.BeginTransaction();
    //    try
    //    {
    //        DataTable dtCustomerList = (DataTable)dgCustomerList.DataSource;
    //        for (int i = 0; i < dgCustomerList.VisibleRowCount; i++)
    //        {
                
    //            if (dgCustomerList.Selection.IsRowSelected(i))
    //            {   
    //                int iInvId = Convert.ToInt32(dtCustomerList.Rows[i]["T_RELATION_INVITATION_ID"]);
    //                int iEventId = Convert.ToInt32(dtCustomerList.Rows[i]["T_RELATION_EVENT_ID"]);
    //                DBQuery.CustomerTable.UpdateStatusHadir(dbl, iInvId, iEventId);
    //            }
    //        }

    //        // COMMIT 
    //        dbl.EndTransaction(true);
    //        bSaved = true;
    //        InitGuestInvitation();
    //        dgCustomerList.Columns["STATUS_HADIR"].Visible = true;
    //    }
    //    catch (Exception ex)
    //    {
    //        // ROLLBACK
    //        dbl.EndTransaction(false);
    //        throw ex;
    //    }
        
    //}
    private void SaveKehadiran()
    {
        DataTable dtOld = DBQuery.CustomerTable.GetCustomerInvitation(m_iEventId, ICPUser.ID);
        DataTable dtUpdate = (DataTable)dgCustomerList.DataSource;

        DBLib dbl = new DBLib();
        dbl.BeginTransaction();
        try
        {
            for (int i = 0; i < dtOld.Rows.Count; i++)
            {
                bool IsOldSelected = dtOld.Rows[i]["STATUS_HADIR"].ToString() == "HADIR";
                int iInvId = Convert.ToInt32(dtOld.Rows[i]["T_RELATION_INVITATION_ID"]);
                int iEventId = Convert.ToInt32(dtOld.Rows[i]["T_RELATION_EVENT_ID"]);
                bool IsNewSelected = dgCustomerList.Selection.IsRowSelectedByKey(dtOld.Rows[i]["T_RELATION_INVITATION_ID"]);

                if (IsOldSelected && !IsNewSelected)
                {
                    DBQuery.CustomerTable.UpdateStatusHadir(dbl, iInvId, iEventId, false);
                }
                else if (!IsOldSelected && IsNewSelected)
                {
                    DBQuery.CustomerTable.UpdateStatusHadir(dbl, iInvId, iEventId, true);
                }
            }
            // COMMIT 
            dbl.EndTransaction(true);
            bSaved = true;
            InitGuestInvitation();
        }
        catch (Exception ex)
        {
            // ROLLBACK
            dbl.EndTransaction(false);
            throw ex;
        }

    }
    
    //public void SendMailExample()
    //{
    //    String sxBekgron = Server.MapPath("~/persib-bandung.gif");
    //    String sxAttachment = Server.MapPath("~/upload/events/201012160950408166893_Laporan Tim Kerja Kasus Munir ke Paripurna DPR.pdf");

    //    Mailer mail = new Mailer();
    //    mail.EmailSender = new System.Net.Mail.MailAddress("donot-reply@icp.lintasarta.co.id", "ICP Bots");
    //    mail.EmailSubject = "You have been notified";
    //    mail.AddAttachment(sxAttachment);
    //    mail.AddRecipient("bayuardi.rahmanto@lintasarta.co.id");
    //    mail.AddCC("irfan.hilmy@lintasarta.co.id");
    //    mail.EmbeddedImage = sxBekgron;
    //    mail.EmailPlainText = "email Anda ga support HTML weeeee :P";
    //    mail.EmailHTMLBody = "<marquee><font size=\"36\" color=\"blue\">HIDUP PERSIBBBBB</font></marquee>";

    //    //mail.SendMail();
    //}
    private string HandleClosing(string sxParam)
    {
        String[] sxSplitted = sxParam.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);

        String sxOutput = String.Empty;

        if (sxSplitted[0].ToUpper().Equals("CLOSE"))
        {
            foreach (String sxRow in sxSplitted)
            {
                String[] sxRowSplitted = sxRow.Split(new String[] { KGlobal.NEWLINE }, StringSplitOptions.None);

                switch (sxRowSplitted[0].ToUpper())
                {
                    case KUFT.EVENTATTACHMENTID:
                        m_uftData.iEventAttachmentId = Int32.Parse(sxRowSplitted[1]);
                        break;
                    case KUFT.PRESENTATIONID:
                        m_uftData.iPresentationId = Int32.Parse(sxRowSplitted[1]);
                        break;
                }
                m_uftData.iEventId = m_iEventId;
            }
            DBQuery.EventTable.CloseEvent(m_uftData);
            bCheckClose = true;
            sxOutput = m_uftData.BuildFieldSet_UFTData();
        }

        return sxOutput;
    }
    private String HandleConfirm(String sxParameter)
    {
        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);

        String sxOutput = String.Empty;
        int iInvID = -1;
        switch (sxSplitted[0].ToUpper())
        {
            case "REASON":
                iInvID = Convert.ToInt32(sxSplitted[1]);
                sxOutput = UFTManager.BuildEditor_Reason(iInvID.ToString());
                break;
            case "SUBMIT":
                iInvID = Convert.ToInt32(sxSplitted[1]);
                int iReasonId = Convert.ToInt32(sxSplitted[2]);
                DBQuery.CustomerTable.SaveReasonNotAttend(iInvID, iReasonId);
                //DBQuery.CustomerVisitTable.EditVisitDatetime(iCVID, dtmVisitDatetime);
                //InitVisitList(m_sxMode);
                break;
            case "DIRECTGUEST":
                DataTable dt = (DataTable)dgCustomerList.DataSource;
                List<int> lstId = new List<int>();
                foreach (DataRow dr in dt.Rows)
                {
                    lstId.Add(Convert.ToInt32(dr["CUSTOMER_ID"]));
                }
                int iCustId = Convert.ToInt32(sxSplitted[1]);
                if (!lstId.Contains(iCustId))
                {
                    InvitationData invData = new InvitationData();
                    invData.intCustID = iCustId;
                    invData.intEventID = Convert.ToInt32(m_sxEventId);
                    invData.sxStatusLain = null;
                    DBLib dbl = new DBLib();
                    DBQuery.CustomerTable.SaveInvitation(dbl, invData);
                }
                break;
        }
        return sxOutput;
    }
    public static String GetInviteColumn(String sxId, String sxCustomerId)
    {
        String sxOutput = String.Empty;
        sxOutput = String.Format(
                "<a href=\"javascript:InviteGuest('{0}','{1}');\">Invite</a>",
                sxId, sxCustomerId);
        return sxOutput;
    }

    private void InitGuest()
    {
        if (Session[KSession.UFT_GUEST] != null)
        {
            int iCompanyId = Convert.ToInt32(Session[KSession.UFT_GUEST]);
            Cached.ContactPersonTable cachedCP = new Cached.ContactPersonTable();
            DataTable dtCP = cachedCP.GetContactPersonList(iCompanyId);
            dgGuest.DataSource = dtCP;
            dgGuest.DataBind();
        }
    }
    private void InitSelectedGuest(String sxParameter)
    {
        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);
        int iCompanyId = Convert.ToInt32(sxSplitted[2]);
        int iInvitationId = Convert.ToInt32(sxSplitted[1]);
        DataTable dtExistingGuest = DBQuery.CustomerTable.getExistingGuest2(iInvitationId);
        dgGuestSelected.DataSource = dtExistingGuest;
        dgGuestSelected.DataBind();
    }
    private void HandleGuest(String sxParameter)
    {
        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);
        int iCompanyId = Convert.ToInt32(sxSplitted[2]);
        Session[KSession.UFT_GUEST] = iCompanyId;
        InitGuest();
    }
    private void HandleSelectGuest(String sxParameter)
    {
        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);
        int iInvId = Convert.ToInt32(sxSplitted[1]);
        DBLib dbl = new DBLib();
        dbl.BeginTransaction();
        try
        {
            DataTable dtGuest = (DataTable)dgGuest.DataSource;
            List<object> keyValues = dgGuest.GetSelectedFieldValues("ID_COMBINED");
            foreach (object obj in keyValues)
            {
                String[] sxIDSplitted = obj.ToString().Split('_');
                bool IsNewCP = sxIDSplitted[1].ToUpper() == KGlobal.YES;
                int iCPId = Convert.ToInt32(sxIDSplitted[0]);
                GuestData guestData = new GuestData();
                if (IsNewCP)
                {
                    guestData.iNewCPId = iCPId;
                }
                else
                {
                    guestData.iCPId = iCPId;
                }
                guestData.sxCreatedBy = ICPUser.ID;
                guestData.iInvitationId = iInvId;
                DBQuery.CustomerTable.SaveGuest(dbl, guestData);
                guestData = null;
            }
            dbl.EndTransaction(true);
            InitSelectedGuest("INIT" + KGlobal.DELIMITER + sxSplitted[1] + KGlobal.DELIMITER + sxSplitted[2]);
        }
        catch (Exception ex)
        {
            dbl.EndTransaction(false);
            throw ex;
        }
    }
    #endregion Custom Methods
}
